//
//  TFHorizontalChatView.swift
//  TalkfunSDKDemo
//
//  Created by 莫瑞权 on 2022/4/25.
//  Copyright © 2022 Talkfun. All rights reserved.
//

import UIKit

typealias TFHorizontalChatViewClickBlock = () -> Void
class TFHorizontalChatView: UIView , UITableViewDelegate,TFChatCellDelegate,TFVoteCellDelegate,UITableViewDataSource,UIScrollViewDelegate {
    
    @objc public weak var delegate : TFHorizontalChatViewDelegate?
    @objc public var tapGestueBlock: TFHorizontalChatViewClickBlock?
    @objc public let tableView = UITableView()
    @objc public let scrollView = UIScrollView()
    @objc public let dataSource = NSMutableArray()
    @objc public var urlArr = NSMutableArray()
    @objc public var url:NSString = ""
    @objc public let gl = CAGradientLayer()
    //滚动到回复的cell
    @objc public var replyrow:NSInteger = 0

    override init(frame: CGRect) {
        super.init(frame: frame)

        self.backgroundColor = UIColor.clear
        self.scrollView.delegate = self
        self.scrollView.showsHorizontalScrollIndicator = false
        self.scrollView.showsVerticalScrollIndicator = false
        self.scrollView.clickGesture(target: self, action: #selector(doubleTapActionClick))
        self.addSubview(self.scrollView)
        self.tableView.backgroundColor = UIColor.clear
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.separatorStyle = .none
        self.tableView.showsVerticalScrollIndicator = false
        self.tableView.showsHorizontalScrollIndicator = false
       let tap = UITapGestureRecognizer.init(target: self, action:#selector(hortapClick))
        self.tableView.addGestureRecognizer(tap)
        self.scrollView.addSubview(self.tableView)
      

        
        self.tableView.register(TFVoteCell.self, forCellReuseIdentifier: "TFVoteCell")
        self.tableView.register(TFMemberCell.self, forCellReuseIdentifier: "TFMemberCell")
        self.tableView.register(TFDisableChatCell.self, forCellReuseIdentifier: "TFDisableChatCell")
        self.tableView.register(TFQuestionCell.self, forCellReuseIdentifier: "TFQuestionCell")
        self.tableView.register(TFChatCell.self, forCellReuseIdentifier: "TFChatCell")
        
    }
    @objc func hortapClick()
    {
        if (self.tapGestueBlock != nil) {
            self.tapGestueBlock!()
        }
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        self.scrollView.frame = self.bounds
        self.scrollView.contentSize = CGSize(width: 0, height: self.bounds.size.height+10)
        self.gl.startPoint = CGPoint(x: 0.5, y: 0)
        self.gl.endPoint = CGPoint(x: 0.5, y: 1)
        self.gl.colors = [UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 0).cgColor, UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 0.50).cgColor ,UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1).cgColor]
        self.gl.locations = [0,1,1]
        self.gl.frame = self.scrollView.frame
        self.scrollView.layer.mask = self.gl;
        
    }
    /**更新聊天信息*/
    @objc public func update_Chat(model:TF_LivingChatData)
    {
        self.dataSource.add(model)
        self.upDateTableviewFrame()
    }
    @objc func ChatDel(uuid:String)
    {
        let copyArray = NSMutableArray.init(array: self.dataSource)
        for i in 0..<copyArray.count {
            let obj = self.dataSource[i] as! NSObject
            if (obj is TF_LivingChatData) {
                let data = obj as! TF_LivingChatData
                
                if (data.uuid == uuid) {
                   
                        self.dataSource.remove(data)

                        break;
                    }
                
            }
        }
       
        self.tableView.reloadData()
      
    }
    /**更新通知信息*/
    @objc public func updata_Notice(model:TFBroadcast)
    {
        self.dataSource.add(model)
        self.upDateTableviewFrame()
    }

    /**更新禁言信息*/
    @objc public func update_disabelChat(model:TFDisableChatModel)
    {
        self.dataSource.add(model)
        self.upDateTableviewFrame()
    }

    /**更新投票信息*/
    @objc public func update_Vote(model:TFVoteData)

    {
        self.dataSource.add(model)
        self.upDateTableviewFrame()
    }

    /**更新抽奖*/
    @objc public func update_Lottery(model:TFLotteryStop)

    {
        self.dataSource.add(model)
        self.upDateTableviewFrame()
    }
    /**回复提问*/
    @objc public func pePly_Question(model:TFQuestionData)
    {
        let copyArray = NSMutableArray.init(array: self.dataSource)
        
        var answer:Bool = false
        for i in 0..<copyArray.count {

            let obj = copyArray[i] as! NSObject
            if (obj is TFQuestionData) {
                let data = obj as! TFQuestionData
                //本地自己的提问中是否查询到
                 if (data.qid == model.qid) {
                     answer = true
                     self.dataSource.replaceObject(at: i, with: model)
                     //[self.dataSource replaceObjectAtIndex:i withObject:model];
                     if (model.isMe) {
                         self.replyrow = i;
                       
                     }
                    break;
                }
            }

        }
        
        //新增新的
        if (answer==false) {
            self.dataSource.add(model)
    
        }
        self.upDateTableviewFrame()
    }
    /**接收提问*/
   @objc public func update_Question(model:TFQuestionData)

    {
        self.dataSource.add(model)
        self.upDateTableviewFrame()
    }
    /**删除提问*/
    @objc public func remove_Question(model:TFQuestionData)

    {
        let copyArray = NSMutableArray.init(array: self.dataSource)
        for i in 0..<copyArray.count {
            let obj = self.dataSource[i] as! NSObject
            if (obj is TFQuestionData) {
                let data = obj as! TFQuestionData
                if (data.qid == model.qid) {
                    if (model.deleteQuestionID.count > 0) {
                        
                        for i in 0..<data.answer.count {
                            let answer = data.answer[i] as! TFQuestionAnswer

                            if (answer.qid == model.deleteQuestionID) {

                                data.answer.remove(answer)
                                break;
                            }
                        }
                    } else {
                        self.dataSource.remove(data)

                        break;
                    }
                }
            }
        }
        self.tableViewReloadData()
    }
    /**其他用户进入直播间*/
    @objc public func update_Join(model:TFMember)

    {
        self.dataSource.add(model)
        self.upDateTableviewFrame()
        
    }

    func upDateTableviewFrame()
    {
        var chatRecordH = self.frame.size.height;
        var cellHeight:CGFloat = 0;
        for i in 0..<self.dataSource.count {
            let result = self.dataSource[i] as! NSObject
            cellHeight = cellHeight + TFHorizontalChatView.getHeight(result: result,width: self.tableView.frame.width,interval:4,imageWidth:68)
        }
        //所有cell 叠加的高度 <
        if (cellHeight<chatRecordH) {

            chatRecordH = cellHeight;
             self.scrollView.isScrollEnabled = true
        }else{
            chatRecordH = self.frame.size.height
            self.scrollView.isScrollEnabled = false

        }
        let chatRecordY:CGFloat = self.frame.size.height - chatRecordH
         self.tableView.frame = CGRect(x: 0, y: chatRecordY, width: self.frame.size.width, height: chatRecordH)
        self.tableViewReloadData()
    }
    func tableViewReloadData()
    {
        
        self.tableView.reloadData()
        
        self.scorellToreplyCell()

    }
    
   @objc public func scorellToreplyCell()
    {
        if self.dataSource.count>0 {
            let indexpath = NSIndexPath.init(row: self.dataSource.count - 1, section: 0)
            self.tableView.scrollToRow(at: indexpath as IndexPath, at: .bottom, animated: true)
        }
        
        
    }
    //区间
    @objc public static func getHeight(result:NSObject ,width:CGFloat ,interval:CGFloat,imageWidth:CGFloat)->CGFloat
    {
        
        if (result is TFBroadcast) { //通知
            let model = result as! TFBroadcast
            
            let AttributedString = NSMutableAttributedString.init(string: model.msg)
            
            let font14 = UIFont.PingFang(size: 14)
            let attr14: [NSAttributedString.Key : Any] = [.font: font14 as Any,]
            AttributedString.addAttributes(attr14, range: NSRange(location: 0, length: AttributedString.length))

            let size = TalkfunSharedTools.getSizeLabel(labelString: AttributedString, labelWidth:width-24-50, labelfont: font14)
            
            
            
            return size.height+interval+12
        } else if (result is TFDisableChatModel) { //禁言
            return 32+interval;
        } else if (result is TFVoteData) { // 投票
            return 30+interval;
        }  else if (result is TFMember) { //用户进入直播间
            return 32+interval;
        }
        else if (result is TFLotteryStop) {  //抽奖
            var str = "抽奖已结束,恭喜" as String
            let model = result as! TFLotteryStop
            let t:Int = model.winnerList.count
            for i in 0..<t {

                let winner = model.winnerList[i] as! TFLotteryWinner
                if (i>3) {
                    if (i==4) {
                        str = str + winner.nickname + "..."

                    }
                } else {
                    if (i==t-1) {
                        str = str + winner.nickname

                    } else {
                        str = str + winner.nickname + "、"

                    }
                }
               
            }
            let allstr = str + String.init(format: "等%ld人中奖", model.winnerList.count)
    
            let AttributedString = NSMutableAttributedString.init(string: allstr)
            
            let font14 = UIFont.PingFang(size: 14)
            let attr14: [NSAttributedString.Key : Any] = [.font: font14 as Any,]
            AttributedString.addAttributes(attr14, range: NSRange(location: 0, length: allstr.count))
     
            let size = TalkfunSharedTools.getSizeLabel(labelString: AttributedString, labelWidth:width-28-32, labelfont: font14)
            
            return size.height+14+interval;
        }
        else if (result is TFQuestionData) { //提问
            let font14 = UIFont.PingFang(size: 14)
            let model = result as! TFQuestionData
            let nickname = model.nickname + " "
            let str11 = (nickname + model.content) as String
            
            let AttributedString = NSMutableAttributedString.init(string: str11)
            let size = TalkfunSharedTools.getSizeLabel(labelString: AttributedString, labelWidth:width-35-16-12-16, labelfont: font14)
            
            if (model.answer.count > 0) {
                var height:CGFloat = 0
                var anserwidth:CGFloat = 0
                for i in 0..<model.answer.count {

                     let answer = model.answer[i] as! TFQuestionAnswer
                 
                    
                    let str = (answer.nickname + answer.content) as String
                    let AttributedString = NSMutableAttributedString.init(string: str)

                    let font14 = UIFont.PingFang(size: 14)
                    let attr14: [NSAttributedString.Key : Any] = [.font: font14 as Any,]
                    AttributedString.addAttributes(attr14, range: NSRange(location: 0, length: AttributedString.length))
                    
                    
                    
                    let attch = NSTextAttachment()
                    attch.bounds = CGRect(x: 0, y: -3, width: 27, height: 15)
                   
                    let imageStr = NSAttributedString.init(attachment: attch)
                    

                    
                    AttributedString.insert(NSAttributedString.init(string: "  "), at: answer.nickname.count)
                  
                    AttributedString.insert(imageStr, at:  answer.nickname.count+" ".count)
                    
                    

                    AttributedString.addAttribute(NSAttributedString.Key.kern, value: (5), range: NSRange(location: answer.nickname.count+2, length: 1))


                    AttributedString.addAttributes(attr14, range: NSRange(location: 0, length: AttributedString.length))
                    
                    
                    let answersize = TalkfunSharedTools.getSizeLabel(labelString: AttributedString, labelWidth:width-35-16-12-16, labelfont: font14)
                    
                    
                    height = height+answersize.height+10
                  
                   //取最大值
                    if answersize.width>anserwidth {
                        anserwidth = answersize.width
                    }
                }
              
                return size.height+10+1+height+interval;

            } else {
                
                return size.height+12+interval;
               
            }
            
          
        }  else {
            //聊天
            let model = result as! TF_LivingChatData
            let height = self.getChatHeight_1(model: model,width:width,interval:interval,imageWidth:imageWidth )
            
            return height

        }
        
      
      
    }
    static func  getChatHeight_1(model:TF_LivingChatData,width:CGFloat,interval:CGFloat,imageWidth:CGFloat)->CGFloat
    {
       
        let msgColor = UIColor(red: 20/255.0, green: 23/255.0, blue: 26/255.0, alpha: 1)

                var roleStr = ""
              if (model.role == .roleSpadmin) {
                    roleStr = "老师"
        
                }
                //=============== 如果是助教说的话 =================
             else if (model.role == .roleAdmin)
                {
                    roleStr = "助教"

                }
       
        if (model.imageURL.count>0) {
            model.msg = "";
        } else {
            model.msg = model.msg;
        }
        let nickname = model.nickname + " "
        let str = nickname + model.msg

        
        let contentDict = TalkfunSharedTools.assembleAttributeString(str, boundingSize: CGSize(width: width-35-16-12-16, height: CGFloat.greatestFiniteMagnitude), fontSize: 14, shadow: false)
        
        let attr:NSAttributedString = contentDict["attributeStr"] as! NSAttributedString

        let AttributedString = NSMutableAttributedString.init(attributedString: attr)

        let attr14: [NSAttributedString.Key : Any] = [.font: UIFont.PingFang(size: 14) as Any,.foregroundColor: msgColor,]
        AttributedString.addAttributes(attr14, range: NSRange(location: 0, length: attr.length))

       
        
        if (roleStr.count > 0) {
            let attch = NSTextAttachment()
           
            attch.bounds = CGRect(x: 0, y: -3, width: 27, height: 15)

            let imageStr = NSAttributedString.init(attachment: attch)
            AttributedString.insert(imageStr, at: model.nickname.count+1)

            AttributedString.insert(NSAttributedString.init(string: " "), at: model.nickname.count+2)

            AttributedString.addAttribute(NSAttributedString.Key.kern, value: (5), range: NSRange(location: model.nickname.count+2, length: 1))
    
        }
        
        let size = TalkfunSharedTools.getSizeLabel(labelString: AttributedString, labelWidth:width-35-16-12-16, labelfont: UIFont.PingFang(size: 14))
       
        var imgHeight:CGFloat = 0
        if (model.imageURL.count > 0) {
            if ( (model.image.size.width == model.image.size.height)) {
                imgHeight = imageWidth + 8;
            } else if ( (model.image.size.width > model.image.size.height)) {
                let proportion:CGFloat = model.image.size.width / imageWidth;
                imgHeight = model.image.size.height / proportion + 8;
            } else if ( (model.image.size.width < model.image.size.height)){
                imgHeight = imageWidth + 8;
            }
        } else {
            imgHeight = 0;
        }
        
        return size.height+12+imgHeight+interval;
    }
    func urlClick(url: NSString) {
        
        if self.delegate != nil && (self.delegate?.responds(to: #selector(TFHorizontalChatViewDelegate.HorChat_clickToUrl(_:))))!{
           
            self.delegate?.HorChat_clickToUrl(url)
        }
       
    }
    
    func clickVote(_ model: TFVoteData) {
        
        if self.delegate != nil && (self.delegate?.responds(to: #selector(TFHorizontalChatViewDelegate.HorChat_clickToUrl(_:))))!{
           
            self.delegate?.HorVote_clickToDetail(model)
        }
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSource.count;
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let result = self.dataSource[indexPath.row] as! NSObject
        let height = TFHorizontalChatView.getHeight(result: result,width: self.tableView.frame.width,interval:4,imageWidth:68)
        return height;

    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let obj = self.dataSource[indexPath.row] as! NSObject
        if (obj is TFBroadcast) { //通知
        
            let cell = tableView.dequeueReusableCell(withIdentifier: "TFVoteCell") as! TFVoteCell
            cell.selectionStyle = .none
            cell.isOrientationLandscape = true
            cell.tf_width = self.frame.size.width;
            cell.backgroundColor = UIColor.clear
            cell.selectionStyle = .none
            let model = self.dataSource[indexPath.row] as! TFBroadcast
            cell.model = model
            cell.delegate = nil
            return cell;
        } else if (obj is TFVoteData) {  //投票
            let cell = tableView.dequeueReusableCell(withIdentifier: "TFVoteCell") as! TFVoteCell
            cell.selectionStyle = .none
            cell.tf_width = self.frame.size.width;
            cell.isOrientationLandscape = true;
            cell.backgroundColor = UIColor.clear

            let model = self.dataSource[indexPath.row] as! TFVoteData
            cell.votemodel = model
            cell.delegate = self
            return cell;
        } else if (obj is TFLotteryStop) { // 抽奖
            let cell = tableView.dequeueReusableCell(withIdentifier: "TFVoteCell") as! TFVoteCell
            cell.selectionStyle = .none
            cell.isOrientationLandscape = true
            cell.tf_width = self.frame.size.width;
            cell.backgroundColor = UIColor.clear

             let model = self.dataSource[indexPath.row] as! TFLotteryStop
            cell.LotteryStopmodel = model;
            cell.delegate = nil;
            return cell;
        } else if (obj is TFMember) {
            let cell = tableView.dequeueReusableCell(withIdentifier: "TFMemberCell") as! TFMemberCell
            cell.selectionStyle = .none
            cell.backgroundColor = UIColor.clear
            cell.isOrientationLandscape = true

            cell.cellwidth = self.frame.size.width
            let model = self.dataSource[indexPath.row] as! TFMember
            cell.model = model;
            return cell
            
        }
        else if (obj is TFDisableChatModel) { //禁言
            let cell = tableView.dequeueReusableCell(withIdentifier: "TFDisableChatCell") as! TFDisableChatCell
            cell.selectionStyle = .none
            cell.isOrientationLandscape = true
            cell.backgroundColor = UIColor.clear

             let model = self.dataSource[indexPath.row] as! TFDisableChatModel
            cell.model = model;
            return cell;
        } else if (obj is TFQuestionData) { // 提问
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "TFQuestionCell") as! TFQuestionCell
            cell.selectionStyle = .none
            cell.cellwidth = self.frame.size.width;
            cell.isQuestion = false
            cell.isOrientationLandscape = true
            cell.isChatArea = true
            cell.backgroundColor = UIColor.clear

            let model = self.dataSource[indexPath.row] as! TFQuestionData
        
            cell.model = model
            return cell;
        } else {  //聊天
            let cell = tableView.dequeueReusableCell(withIdentifier: "TFChatCell") as! TFChatCell
            cell.selectionStyle = .none
            cell.cellwidth = self.frame.size.width
            cell.backgroundColor = UIColor.clear

            cell.isOrientationLandscape = true
           
             let model = self.dataSource[indexPath.row] as! TF_LivingChatData
              
            cell.model = model

            cell.delegate = self
            return cell;
        }
        
    }
    
   
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.doubleTapActionClick()
        let obj = self.dataSource[indexPath.row] as! NSObject
        
         if (obj is TFVoteData) { //投票
             let model = self.dataSource[indexPath.row] as! TFVoteData
             
             self.clickVote(model)

           
        }
    }
    
    
    @objc func doubleTapActionClick()
    
    {
        NotificationCenter.default.post(name: Notification.Name(rawValue: "LarGeLivekeyboardWillHide"), object: nil)
    }

    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.doubleTapActionClick()
    }
}
@objc protocol TFHorizontalChatViewDelegate : NSObjectProtocol {
    // 点击超链接
    func HorChat_clickToUrl(_ url :NSString)
    //投票结果
    func HorVote_clickToDetail(_ model :TFVoteData)

}
